/*
 * @Author: your name
 * @Date: 2021-04-06 09:49:41
 * @LastEditTime: 2021-04-09 13:44:31
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \v3-ts\src\utils\index.ts
 */

type TYPE_NAME =
  | 'string'
  | 'boolean'
  | 'number'
  | 'object'
  | 'null'
  | 'undefined'
  | 'array'
  | 'symbol'
  | 'date';

/**
 * @description: 判断数据的类型
 * @param {Any} data - 需要判断的数据
 * @param {TYPE_NAME} type - 数据的类型
 * @return {Boolean} true/false - 数据类型是否正确
 * @author: 颜锦忠
 */
export const typeOf = (data: any, type: TYPE_NAME): boolean => {
  const res = Object.prototype.toString.call(data);
  res.substring(8, res.length - 1).toLowerCase();
  return res === type;
};

/**
 * @description: 实现从深度优先的角度进行深拷贝
 * @param {Any} data - 深拷贝的数据源
 * @param {Array} visitedArray - 存储数据的数组对象
 * @return {Any} 返回深拷贝过后的对象数据
 * @author: 颜锦忠
 */

export const DFSDeepClone = <T>(data: T, visitedArray: Array<any> = []): T => {
  let _obj;
  if (data != null && typeof data === 'object') {
    const index = visitedArray.indexOf(data as never);
    _obj = Array.isArray(_obj) ? [] : {};
    if (~index) {
      _obj = visitedArray[index];
    } else {
      visitedArray.push(_obj as never);
      for (const item in _obj) {
        _obj[item] = DFSDeepClone(_obj[item], visitedArray);
      }
    }
  } else if (typeof data === 'function') {
    _obj = eval('(' + data.toString() + ')');
  } else {
    _obj = data;
  }
  return _obj;
};

/**
 * @description: 数字每隔3位添加分号
 * @param {*}
 * @return {*}
 * @author: 颜锦忠
 */
export const numberThousands = (num: number): string => {
  const n = num.toString();
  const reg = /(\d)(?=(\d{3})+\.)/g;
  const decimal = /(\d)(?=(\d{3})+$)/g;

  return n.replace(n.indexOf('.') > -1 ? reg : decimal, '$1,');
};

/**
 * @description: 将小数转化位百分比
 * @param {*}
 * @return {*}
 * @author: 颜锦忠
 */
export const numberPercentage = (num: number | string, digit = 2): string => {
  const res = Math.abs(+num * 100).toFixed(digit) + '%';
  return res;
};

/**
 * @description: 获取指定范围的随机数
 * @param {*}
 * @return {*}
 * @author: 颜锦忠
 */

export const numberRandom = (min: number, max: number): number => {
  const result = Math.floor(Math.random() * (max - min + 1)) + min;
  return result;
};

/**
 * @description: 复制文本
 * @param {*}
 * @return {*}
 * @author: 颜锦忠
 */
export const copy = (content: string, callback: any): void => {
  if (!document.queryCommandSupported('copy')) {
    console.log('该浏览器不支持复制');
    return;
  }
  const textarea = document.createElement('textarea');
  textarea.value = content;
  textarea.readOnly = true;
  document.body.appendChild(textarea);
  textarea.select();
  textarea.setSelectionRange(0, content.length);

  const result = document.execCommand('copy');
  callback && callback(result ? '复制成功' : '复制失败');
  textarea.remove();
};
